#用于进行http请求，以及MD5加密，生成签名的工具类
#适用于OkCoin
import http.client
import urllib
import json
import hashlib


def buildMySign(params, secretKey):
    sign = ''
    for key in sorted(params.keys()):
        sign += key + '=' + str(params[key]) +'&'
    data = sign+'secret_key='+secretKey
    return hashlib.md5(data.encode("utf8")).hexdigest().upper()


def httpGet(url, resource, params=''):
    conn = http.client.HTTPSConnection(url, timeout=1)
    conn.request("GET", resource + '?' + params)
    response = conn.getresponse()
    data = response.read().decode('utf-8')
    conn.close()
    return json.loads(data)


def httpPost(url, resource, params):
    headers = {
            "Content-type" : "application/x-www-form-urlencoded",
     }
    conn = http.client.HTTPSConnection(url, timeout=3)
    temp_params = urllib.parse.urlencode(params)
    conn.request("POST", resource, temp_params, headers)
    response = conn.getresponse()
    data = response.read().decode('utf-8')
    conn.close()
    return json.loads(data)


def sort_and_format(l, reverse=False):
    l.sort(key=lambda x: float(x[0]), reverse=reverse)
    r = []
    for i in l:
        r.append({'price': float(i[0]), 'volume': float(i[1])})
    return r
